<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item
        v-for="(item,index) in  inquiryZxj"
        :key="index"
        :label="item.label"
        :prop="item.prop"
      >
        <el-input
          :placeholder="item.placeholder"
          v-model="queryParams[item.prop]"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >搜索
        </el-button>
        <el-button
          icon="el-icon-refresh"
          size="mini"
          @click="resetQuery"
        >重置
        </el-button>
      </el-form-item>
    </el-form>

    <el-row
      :gutter="10"
      class="mb8"
    >
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['student:zxj:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-view"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >查看
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['student:zxj:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['student:zxj:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <el-table
      border
      fit
      highlight-current-row
      v-loading="loading"
      :data="zxjList"
      @selection-change="handleSelectionChange"
    >
      <!-- @sort-change="sortChange" -->
      <el-table-column
        type="selection"
        width="45"
        align="center"
      ></el-table-column>
      <el-table-column
        label="序号"
        prop="zxjId"
        sortable="custom"
        align="center"
        width="75"
      />

      <el-table-column
        label="时间"
        prop="createTime"
        width="170px"
        align="center"
      ></el-table-column>
      <el-table-column
        label="学号"
        align="center"
        prop="xuehao"
        width="125"
      ></el-table-column>
      <el-table-column
        label="姓名"
        align="center"
        prop="userName"
        width="75"
      ></el-table-column>
      <el-table-column
        label="班级"
        align="center"
        prop="deptName"
      ></el-table-column>
      <el-table-column
        label="证件类型"
        align="center"
        prop="userIdcardtype"
        width="180"
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.stu_user_cardtype"
            :value="scope.row.userIdcardtype"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="证件号"
        align="center"
        prop="userIdno"
        width="200"
      ></el-table-column>
      <el-table-column
        label="审核状态"
        align="center"
        prop="status"
        width="125"
      >
        <template slot-scope="{row}">
          <el-tag
            type="info"
            v-show="row.status==='0'"
          >
            审核中
          </el-tag>
          <el-tag
            type="success"
            v-show="row.status==='2'"
          > 已通过
          </el-tag>
          <el-tag
            type="danger"
            v-show="row.status==='1'"
          > 未通过
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column
        width="135"
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">

          <el-button
            size="mini"
            type="primary"
            icon="el-icon-view"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['student:zxj:query']"
            style="padding:5px"
          > 查看
          </el-button>
          <el-button
            size="mini"
            type="danger"
            icon="el-icon-delete"
            style="padding:5px"
            @click="handleDelete(scope.row)"
            v-hasPermi="['student:zxj:remove']"
          > 删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或查看助学金对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="600px"
      append-to-body
    >
      <el-tabs v-model="activeName">
        <el-tab-pane label="助学金申请" name="first">
          <el-form
            ref="form"
            :model="form"
            :rules="rules"
            label-width="80px"
          >
            <el-form-item
              label="姓名"
              prop="userName"
            >
              <el-input
                v-model="form.userName"
                placeholder="请输入姓名"
              />
            </el-form-item>
            <el-form-item
              label="证件类型"
              prop="userIdcardtype"
            >
              <el-select
                v-model="form.userIdcardtype"
                placeholder="请选择证件类型"
              >
                <el-option
                  v-for="dict in dict.type.stu_user_cardtype"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item
              label="证件号"
              prop="userIdno"
            >
              <el-input
                v-model="form.userIdno"
                placeholder="请输入证件号"
              />
            </el-form-item>

            <el-form-item
              label="户口性质"
              prop="householdRegister"
            >
              <el-radio-group v-model="form.householdRegister">
                <el-radio label="农村">农村</el-radio>
                <el-radio label="城镇">城镇</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item
              label="家庭人口数"
              prop="familyPopulation"
            >
              <el-input
                v-model.number="form.familyPopulation"
                placeholder="请输入家庭人口数"
              />
            </el-form-item>

            <el-form-item
              label="家庭成员在学人数"
              prop="studyNumber"
            >
              <el-input
                v-model.number="form.studyNumber"
                placeholder="请输入家庭成员在学人数"
              />
            </el-form-item>

            <el-form-item
              label="赡养人数"
              prop="toSupportNumberOf"
            >
              <el-input
                v-model.number="form.toSupportNumberOf"
                placeholder="赡养人数"
              />
            </el-form-item>

            <el-form-item
              label="家庭失业人数"
              prop="numberUnemployedFami"
            >
              <el-input
                v-model.number="form.numberUnemployedFami"
                placeholder="家庭失业人数"
              />
            </el-form-item>

            <el-form-item
              label="健康状态"
              prop="healthStatus"
            >
              <el-radio-group v-model="form.healthStatus">
                <el-radio label="本人残疾">本人残疾</el-radio>
                <el-radio label="学生本人患重大疾病">学生本人患重大疾病</el-radio>
                <el-radio label="健康">健康</el-radio>
              </el-radio-group>
            </el-form-item>


            <el-form-item
              :label="item.label"
              v-for="(item,index) in zxjDialog"
              :key="index"
              v-show="form.zxjId === null||form[item.model]==='1'"
            >
              <el-radio-group v-model="form[item.model]">
                <el-radio
                  v-for="dict in dict.type.zxj_yes_no"
                  :key="dict.value"
                  :label="dict.value"
                >{{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>

            <!--新增时图片上传-->
            <el-form-item
              label="佐证图片"
              prop="uploadFile"
              v-if="form.zxjId === null"
            >
              <el-upload
                class="upload-demo"
                name="uploadFile"
                list-type="picture-card"
                ref="upload"
                :data="form"
                :headers="headers"
                :auto-upload="false"
                :limit=limitNum
                accept=".png,.jpg"
                :on-change="handleChange"
                :on-remove="handleRemove"
                :on-exceed="exceedFile"
                :on-success="handleSuccess"
                :on-error="handleError"
                :http-request="httpRequest"
                action="/dev-api/data/file/fileUpload"
                :file-list="fileList"
                multiple
                :show-file-list="true"
              >

                <el-button
                  size="small"
                  type="primary"
                >上传附件
                </el-button>
                <div
                  slot="tip"
                  class="el-upload__tip"
                  style="float: right;color: #E6A23C"
                >
                  只能上传jpg/png文件，且不超过20Mb。<br>
                  单次上传限制15张，请上传少于15张图片，多的图片可在补充中上传。<br>
                  图片有压缩为正常情况，只是显示不全，提交到后台为原图。
                </div>
              </el-upload>
            </el-form-item>
            <!--查看时图片回显-->

            <el-form-item label="佐证图片" v-if="form.zxjId != null&&src1!=null">
              <el-row>

                <el-image
                  :span="12"
                  v-for="(item,index) in src1"
                  style="width:130px;height:130px;margin:15px"
                  :src="item"
                  :preview-src-list="src1"
                >
                </el-image>

              </el-row>
            </el-form-item>

            <el-form-item
              label="补充"
              prop="stuContent"
            >
              <editor
                v-model="form.stuContent"
                :min-height="192"
              />
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <!--
                <ImagePreview
                  :src="src1"
                  v-if="isShowImage"
                  style="width:50%;height:50%;"
                ></ImagePreview>-->
        <el-tab-pane label="审批" name="second">
          <el-form
            :model="shengpi"
            ref="shengpi"
            label-width="80px"
            v-if="shengpi.status!=0"
          >

            <el-form-item label="总分" prop="score"
            >
              <el-input v-model.number="shengpi.score" style="width:40%"></el-input>
            </el-form-item>

            <el-form-item label="是否通过" prop="status"
            >
              <el-radio-group v-model="shengpi.status">
                <el-radio label="2" border>通过</el-radio>
                <el-radio label="1" border>不通过</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item
              label="理由"
              prop="teaContent"
            >
              <editor
                v-model="shengpi.teaContent"
                :min-height="192"
              />
            </el-form-item>

          </el-form>
          <div v-if="shengpi.status==0">
            <mallki class-name="mallki-text" text="教师暂未进行审批"/>
          </div>
        </el-tab-pane>

      </el-tabs>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          type="primary"
          @click="submitForm"
        >确 定
        </el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listZxj,
  getZxj,
  delZxj,
  addZxj,
  updateZxj,
  addFile,
  getIndexInfo
} from '@/api/student/zxj'
import { getToken } from '@/utils/auth'
import ImagePreview from '@/components/ImagePreview/index'
import Mallki from '@/components/TextHoverEffect/Mallki'

export default {
  name: 'Zxj',
  dicts: ['zxj_yes_no', 'stu_user_cardtype'],
  components: {
    ImagePreview,
    Mallki
  },
  data() {
    return {
      src1: [],
      isShowImage: false,
      labelTitle: [
        '脱贫家庭学生',
        '脱贫不稳定家庭学生',
        '边缘易致贫家庭学生',
        '突发严重苦难户学生',
        '原广东省户籍建档立卡家庭学生',
        '特困供养人员',
        '孤儿',
        '特困职工儿女',
        '城乡最低生活保障户',
        '城镇低收入困难家庭',
        '享受国家定期抚恤补助的优抚对象',
        '学生本人残疾',
        '父亲为残疾人',
        '母亲为残疾人'
      ],
      labelModel: [
        'whetherfamilypoorstudents',
        'whetherstudentsunstablefamilypoverty',
        'whetheredgeeasyfamilypovertystudents',
        'whethermassiveneedystudents',
        'whetherguangddong',
        'whethermostneedysupportpersonnel',
        'whetherorphan',
        'whetherverypoorworkerchildren',
        'urbanruralsecuritydoor',
        'lowincomefamilies',
        'regularsubsidyobject',
        'whetherdisability',
        'hisfatherfordisabl',
        'hismotherfordisabl'
      ],
      //奖学金对话框
      zxjDialog: [],
      // 查询奖学金表单
      inquiryZxj: [
        {
          label: '助学金序号',
          prop: 'zxjId',
          placeholder: '请输入助学金序号'
        },
        {
          label: '用户序号',
          prop: 'userId',
          placeholder: '请输入用户序号'
        },
        {
          label: '姓名',
          prop: 'userName',
          placeholder: '请输入姓名'
        },
        {
          label: '证件号',
          prop: 'userIdno',
          placeholder: '请输入证件号'
        }
      ],
      zxjItem: [
        {
          label: '助学金序号',
          prop: 'zxjId'
        },
        {
          label: '用户序号',
          prop: 'userId'
        },
        {
          label: '姓名',
          prop: 'userName'
        },
        {
          label: '证件号',
          prop: 'userIdno'
        },
        {
          label: '审核状态',
          prop: 'status'
        }
      ],

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 助学金表格数据
      zxjList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        zxjId: null,
        userId: null,
        userName: null,
        userIdno: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userName: [
          { required: true, message: '姓名不能为空', trigger: 'blur' }
        ],
        userIdcardtype: [
          { required: true, message: '证件类型不能为空', trigger: 'change' }
        ],
        userIdno: [
          { required: true, message: '证件号不能为空', trigger: 'blur' }
        ],
        householdRegister: [
          { required: true, message: '户口性质不能为空', trigger: 'change' }
        ],
        familyPopulation: [
          { required: true, message: '家庭人口数不能为空', trigger: 'blur' },
          { type: 'number', message: '家庭人口数必须为数字值' }
        ],
        studyNumber: [
          { required: true, message: '家庭成员在学人数不能为空', trigger: 'blur' },
          { type: 'number', message: '家庭成员在学人数必须为数字值' }
        ],
        toSupportNumberOf: [
          { required: true, message: '赡养人数不能为空', trigger: 'blur' },
          { type: 'number', message: '赡养人数必须为数字值' }
        ],
        numberUnemployedFami: [
          { required: true, message: '家庭失业人数不能为空', trigger: 'blur' },
          { type: 'number', message: '家庭失业人数必须为数字值' }
        ],
        healthStatus: [
          { required: true, message: '健康状态不能为空', trigger: 'change' }
        ]

      },
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      limitNum: 15,
      fileList: [],
      token: {
        accessToken: ''
      },

      //审批表单选项卡默认显示
      activeName: 'first',

      //审批表单
      shengpi: {}
    }
  },
  created() {
    this.getList()
    this.getLabel()
  },
  methods: {

    getLabel() {
      for (const i in this.labelTitle) {
        this.zxjDialog.push({
          label: this.labelTitle[i],
          model: this.labelModel[i]
        })
      }
    },
    /** 查询助学金列表 */
    getList() {
      this.loading = true
      listZxj(this.queryParams).then((response) => {
        this.zxjList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        zxjId: null,
        userId: null,
        userName: null,
        userIdcardtype: null,
        userIdno: null,
        whetherfamilypoorstudents: '0',
        whetherstudentsunstablefamilypoverty: '0',
        whetheredgeeasyfamilypovertystudents: '0',
        whethermassiveneedystudents: '0',
        whetherguangddong: '0',
        whethermostneedysupportpersonnel: '0',
        whetherorphan: '0',
        whetherverypoorworkerchildren: '0',
        urbanruralsecuritydoor: '0',
        lowincomefamilies: '0',
        regularsubsidyobject: '0',
        whetherdisability: '0',
        hisfatherfordisabl: '0',
        hismotherfordisabl: '0',
        householdRegister: null,
        familyPopulation: 0,
        studyNumber: 0,
        toSupportNumberOf: 0,
        numberUnemployedFami: 0,
        healthStatus: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        status: null,
        delFlag: null,
        stuContent: null
      }
      this.src1 = []
      this.shengpi = {
        score: '0',
        status: '',
        teaContent: null
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.zxjId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加助学金'
    },
    /** 查看按钮操作 */
    handleUpdate(row) {
      this.isShowImage = true
      this.reset()
      const zxjId = row.zxjId || this.ids
      getZxj(zxjId).then((response) => {
        this.src1 = response.srcList
        this.form = response.data
        if (row.status != 0) {
          this.shengpi = response.shengpi
        }
        this.shengpi.status = row.status
        this.open = true
        this.title = '查看助学金申请'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.zxjId != null) {
            this.cancel()
            this.open = false
          } else {
            this.submitForm1(this.form)
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const zxjIds = row.zxjId || this.ids
      this.$modal
        .confirm('是否确认删除助学金编号为"' + zxjIds + '"的数据项？')
        .then(function() {
          return delZxj(zxjIds)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'student/zxj/export',
        {
          ...this.queryParams
        },
        `zxj_${new Date().getTime()}.xlsx`
      )
    },

    exceedFile(files, fileList) {
      this.$message({
        message:
          '只能选择' + this.limitNum + '个文件，当前共选择了 ' + (files.length + fileList.length) + '个',
        type: 'danger'
      })
    },

    // 文件状态改变时的钩子
    handleChange(file, fileList) {
      this.filelist = fileList
    },
    // 文件移除时的钩子
    handleRemove(file, fileList) {
      this.filelist = fileList
    },

    // 上传文件之前的钩子, 参数为上传的文件,若返回 false 或者返回 Promise 且被 reject，则停止上传
    beforeUploadFile(file) {
      let testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
      const extension = testmsg === 'png'
      const extension2 = testmsg === 'jpg'
      let size = file.size / 1024 / 1024
      if (!extension && !extension2) {
        this.$message({
          message: '上传文件只能是png、jpg!',
          type: 'danger'
        })
      }
      if (size > 20) {
        this.$message({
          type: 'danger',
          message: `文件大小不得超过20M!`
        })
      }
      return extension || extension2
    },

    // 文件上传成功时的钩子
    handleSuccess(res, file, fileList) {
      this.open = false
      this.getList()
      this.$message({
        type: 'danger',
        message: `文件上传成功!`
      })
    },

    // 文件上传失败时的钩子
    handleError(err, file, fileList) {
      this.$message({
        type: 'danger',
        message: `文件上传失败!`
      })
    },
    submitForm1(form) {
      this.$refs.form.validate((valid) => {
        if (valid) {
          var upData = new FormData() // 首先创建FormData对象
          this.$refs.upload.submit() // 这里是执行文件上传的函数，其实也就是获取我们要上传的文件
          this.fileList.forEach(function(file) {
            upData.append('uploadFile', file, file.name) // 因为要上传多个文件，所以需要遍历一下才行
            // upData.append('file', this.file); 不要直接使用我们的文件数组进行上传，你会发现传给后台的是两个Object
          })
          //遍历表单中的其他参数
          for (let key in this.form) {
            //非空判断
            if (
              this.form[key] != null &&
              this.form[key] != '' &&
              this.form[key] != ' '
            ) {
              upData.append(key, this.form[key])
            }
          }
          //同理: 将每个参数都进行一次此操作 upData.appen(表单参数,form.表单参数)

          //接口调用
          addFile(upData).then((response) => {
            if (response.code === 200) {
              this.$modal.msgSuccess('上传成功！')
              this.$refs.upload.clearFiles() //清空，同this.fileList=[]
              this.fileList = []
              this.open = false
              this.getList()
            } else {
              this.$modal.msgError('上传失败！')
              this.open = false
              this.fileList = [] // 阻止上传的文件被重复添加，所以清空掉
            }
          })
        }
      })
    },
    //拿第一张图片
    imgOnchange1() {
      this.fileList.push(document.querySelector('#img1').files[0])
    },
    // 自定义的上传函数
    httpRequest(param) {
      // 一般情况下是在这里创建FormData对象，但我们需要上传多个文件，为避免发送多次请求，因此在这里只进行文件的获取，param可以拿到文件上传的所有信息
      this.fileList.push(param.file)
    }
  }
}
</script>
<style lang="scss" scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.el-image {
  border-radius: 5px;
  background-color: #ebeef5;
  box-shadow: 0 0 5px 1px #ccc;

  ::v-deep .el-image__inner {
    transition: all 0.3s;
    cursor: pointer;

    &:hover {
      transform: scale(1.2);
    }
  }

  ::v-deep .image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    color: #909399;
    font-size: 30px;
  }



}
</style>
